package com.cntaiping.dataflow.util;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.Temporal;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by xiao_qiang_01@163.com on 2018/6/9.
 **/
public class DateJdk8Util {
    public static final String DATE_FORMAT = "yyyy-MM-dd";
    public static final String DATE_FORMAT_BATCH = "yyyyMMdd";
    public static final String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    public static final String TIME_FORMAT = "HH:mm:ss";
    public static final String ASIA_SHANGHAI = "Asia/Shanghai";
    public static final String EUROPE_PARIS = "Europe/Paris";

    /**
     * 设置日期时间
     *
     * @return 日期时间, 格式 "2017-09-22T10:26:16.268"
     */
    public static LocalDateTime setDateTime(int year, int month, int dayofMonth, int hour, int minute, int second) {
        return LocalDateTime.of(year, month, dayofMonth, hour, minute, second);
    }

    /**
     * 设置日期
     *
     * @return 日期
     */
    public static LocalDate setDate(int year, int month, int dayofMonth) {
        return LocalDate.of(year, month, dayofMonth);
    }

    /**
     * 使用默认时区时钟瞬时时间创建
     *
     * @return 日期时间, 格式 "2017-09-22T10:26:16.268"
     */
    public static LocalDateTime now() {
        return LocalDateTime.now();
    }

    /**
     * 使用自定义时区时钟瞬时时间创建
     *
     * @return 日期时间, 格式 "2017-09-22T10:26:16.268"
     */
    public static LocalDateTime now(String zoneId) {
        return LocalDateTime.now(ZoneId.of(zoneId));
    }

    /**
     * 日期时间字符串转对象
     *
     * @param datetimeStr 格式为 "yyyy-MM-dd HH:mm:ss"
     * @return 返回日期时间对像
     */
    public static LocalDateTime dateTimeFormatter(String datetimeStr) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATETIME_FORMAT);
        return LocalDateTime.parse(datetimeStr, formatter);
    }

    /**
     * 日期时间字符串转对象
     *
     * @param datetimeStr       带时间的日期字符串
     * @param dateTimeFormatter 自定义格式
     * @return 返回日期时间对像
     */
    public static LocalDateTime dateTimeFormatter(String datetimeStr, String dateTimeFormatter) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateTimeFormatter);
        return LocalDateTime.parse(datetimeStr, formatter);
    }

    /**
     * 日期时间字符串转对象
     *
     * @param dateStr 格式为 "yyyy-MM-dd"
     * @return 返回日期时间对像
     */
    public static LocalDate dateFormatter(String dateStr) {
        if (null == dateStr) {
            return null;
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_FORMAT);
        return LocalDate.parse(dateStr, formatter);
    }

    /**
     * 日期时间字符串转对象
     *
     * @param dateStr       日期字符串
     * @param dateFormatter 自定义格式
     * @return 返回日期时间对像
     */
    public static LocalDate dateFormatter(String dateStr, String dateFormatter) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormatter);
        return LocalDate.parse(dateStr, formatter);
    }

    /**
     * 取当前时间的日期字符串
     *
     * @return
     */
    public static String nowStr() {
        return localDateTimeFormatter(now(), DATE_FORMAT);
    }

    /**
     * 取当前时间的日期时间字符串
     *
     * @return
     */
    public static String nowDateTimeStr() {
        return localDateTimeFormatter(now(), DATETIME_FORMAT);
    }

    /**
     * 日期时间对象转字符串(默认转为 yyyy-MM-dd HH:mm:ss)
     *
     * @param datetime 时间日期对象
     * @return 返回格式后的时间日期字符串
     */
    public static String getDateTimeStr(LocalDateTime datetime) {
        return localDateTimeFormatter(datetime, DATETIME_FORMAT);
    }

    /**
     * 日期时间对象 转 日期字符串
     *
     * @param datetime
     * @return
     */
    public static String getDateStr(LocalDateTime datetime) {
        if (datetime == null) {
            return null;
        }
        return localDateTimeFormatter(datetime, DATE_FORMAT);
    }

    /**
     * 日期时间对象 转 日期字符串
     *
     * @param date
     * @return
     */
    public static String getDateStr(LocalDate date) {
        if (date == null) {
            return null;
        }
        return localDateFormatter(date, DATE_FORMAT);
    }

    /**
     * 日期时间对象 转 时间字符串
     *
     * @param datetime
     * @return
     */
    public static String getTimeStr(LocalDateTime datetime) {
        if (datetime == null) {
            return null;
        }
        return localDateTimeFormatter(datetime, TIME_FORMAT);
    }

    /**
     * 日期时间对象转字符串
     *
     * @param datetime  时间日期对象
     * @param formatter 格式化字符串
     * @return 返回格式后的时间日期字符串
     */
    public static String localDateTimeFormatter(LocalDateTime datetime, String formatter) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(formatter);
        return dateTimeFormatter.format(datetime);
    }

    public static String longToDateTimeFormatter(Long datetime) {
        return DateTimeFormatter.ofPattern(DATETIME_FORMAT).format(
                LocalDateTime.ofInstant(Instant.ofEpochMilli(datetime), ZoneId.systemDefault()));
    }

    public static String localDateFormatter(LocalDate date, String formatter) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(formatter);
        return dateTimeFormatter.format(date);
    }

    /**
     * @return 返回昨天日期
     */
    public static LocalDate getYesterday() {
        return LocalDate.now().minusDays(1);
    }

    /**
     * @return 返回明天日期
     */
    public static LocalDate getTomorrow() {
        return LocalDate.now().plusDays(1);
    }

    /**
     * 返回两个日期之间的间隔多少年月日
     *
     * @param date1
     * @param date2
     * @return
     */
    public static Period getPeriodBeteen(LocalDate date1, LocalDate date2) {
        return Period.between(date1, date2);
    }

    /**
     * 返回两个日期之间的间隔多少天，小时，分钟，秒
     *
     * @param date1 必须带时间，可以是 LocalDateTime 或 LocalTime
     * @param date2 必须带时间，可以是 LocalDateTime 或 LocalTime
     * @return
     */
    public static Duration getDurationBeteen(Temporal date1, Temporal date2) {
        return Duration.between(date1, date2);
    }
    /*****************************************************************************************************************
     * ***************************************************************************************************************
     * *******************    Date 与 java8 Date 互相转换   **********************************************************
     * ***************************************************************************************************************
     */
    /**
     * java.util.Date --> java.time.LocalDateTime
     */
    public static LocalDateTime UDateToLocalDateTime(Date date) {
        Instant instant = date.toInstant();
        return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
    }

    /**
     * java.util.Date --> java.time.LocalDate
     */
    public static LocalDate UDateToLocalDate(Date date) {
        Instant instant = date.toInstant();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
        return localDateTime.toLocalDate();
    }

    /**
     * java.util.Date --> java.time.LocalTime
     */
    public static LocalTime UDateToLocalTime(Date date) {
        Instant instant = date.toInstant();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
        return localDateTime.toLocalTime();
    }

    /**
     * java.time.LocalDateTime --> java.util.Date
     */
    public static Date LocalDateTimeToUdate(LocalDateTime localDateTime) {
        Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();
        return Date.from(instant);
    }

    /**
     * java.time.LocalDate --> java.util.Date
     */
    public static Date LocalDateToUdate(LocalDate localDate) {
        Instant instant = localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();
        return Date.from(instant);
    }

    /**
     * 根据生日获取年龄
     *
     * @param birthDay
     * @return
     */
    public static int getAge(Date birthDay) {
        try {
            Calendar cal = Calendar.getInstance();
            if (cal.before(birthDay)) {
                return 0;
            }
            int yearNow = cal.get(Calendar.YEAR);
            int monthNow = cal.get(Calendar.MONTH);
            int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
            cal.setTime(birthDay);
            int yearBirth = cal.get(Calendar.YEAR);
            int monthBirth = cal.get(Calendar.MONTH);
            int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
            int age = yearNow - yearBirth;
            if (monthNow <= monthBirth) {
                if (monthNow == monthBirth) {
                    if (dayOfMonthNow < dayOfMonthBirth) {
                        age--;
                    }
                } else {
                    age--;
                }
            }
            return age;
        } catch (Exception e) {
            return 0;
        }
    }

   /* public static void main(String[] args) {
//计算两个Temporal对象的时间差
        LocalDate date1 = LocalDate.of(2017,8,1);
        LocalDate date2 = LocalDate.now();
        Period period = Period.between(date1,date2);
        System.out.println("date1: "+date1+"\ndate2: "+date2);
        System.out.println("Period->years:"+period.getYears()+" months:"+period.getMonths()+" days:"+period.getDays());
        System.out.println("Duration->" +period.toTotalMonths());
        period.getUnits().forEach( temporalUnit -> System.out.print(temporalUnit+": "+period.get(temporalUnit)+" ") );
        System.out.println("\"----------------------\" = " + "----------------------");
        LocalDateTime tdate1 = LocalDateTime.of(2017,9,20,0,0,0);
        LocalDateTime tdate2 = LocalDateTime.now();
        LocalTime time1 = LocalTime.of(0,0,0);
        LocalTime time2 = LocalTime.now();
        System.out.println("time1: "+time1+"\ntime2: "+time2);
        Duration duration = Duration.between(tdate1,tdate2);
        System.out.println("duration.toHours() = " + duration.toHours());
        System.out.println(localDateTimeFormatter(now(), "yyyy-MM-dd-HH"));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        String synTime = sdf.format(Long.parseLong("1528517700224"));
        System.out.println("BornTimestamp:"  + "____" + synTime);
        System.out.println("BornTimestamp. " +
                longToDateTimeFormatter(Long.valueOf("1528517700224"))
        );

        String count_date="2020-02-05";
        //获取月初
        LocalDate monthOfFirstDate=LocalDate.parse(count_date,
                DateTimeFormatter.ofPattern("yyyy-MM-dd")).with(TemporalAdjusters.firstDayOfMonth());
        //获取月末
        LocalDate monthOfLastDate=LocalDate.parse(count_date,
                DateTimeFormatter.ofPattern("yyyy-MM-dd")).with(TemporalAdjusters.lastDayOfMonth());

        System.out.println(monthOfFirstDate);
        System.out.println(monthOfLastDate);

    }*/


}